package com.irate.fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ipaulpro.afilechooser.utils.FileUtils;
import com.irate.activity.R;
import com.irate.cache.ImageCache.ImageCacheParams;
import com.irate.cache.ImageFetcher;
import com.irate.cache.RecyclingImageView;
import com.irate.dao.UserDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.model.User;
import com.irate.provider.ContentManager;

public class AccountFragment extends Fragment {

	protected RecyclingImageView my_avatar;
	protected TextView my_first_name;
	protected TextView my_last_name;
	protected TextView my_email;
	protected RadioButton my_male;
	protected RadioButton my_female;
	protected Spinner my_age_group;
	protected Spinner my_region;
	protected Button update;
	protected TextView facebookAge;
	protected TextView facebookRegion;
	

	protected ImageFetcher imageFetcher;
	protected static final String IMAGE_CACHE_DIR = "thumbs";
	protected int mImageThumbSize;

	protected ProgressDialog dialog;
	protected Handler handler;

	protected UserDAO userDao;

	protected String avatar_pic;

	private static final String TAG = "FileChooserExampleActivity";

	private static final int REQUEST_CODE = 6384; // onActivityResult request
													// code

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.account_layout, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		init();
		execute();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CODE:
			// If the file selection was successful
			if (resultCode == getActivity().RESULT_OK) {
				if (data != null) {
					// Get the URI of the selected file
					final Uri uri = data.getData();
					Log.i(TAG, "Uri = " + uri.toString());
					try {
						// Get the file path from the URI
						final String path = FileUtils.getPath(getActivity(),
								uri);

						if (path != null) {
							avatar_pic = path;
						} else {
							avatar_pic = getBitmap("avatar.jpg", uri);
						}

						File fileContent = new File(avatar_pic);
						if (fileContent.length() / 1024 < 2000) {
							Bitmap bm = BitmapFactory.decodeFile(avatar_pic);
							my_avatar.setImageBitmap(bm);

							dialog = ProgressDialog.show(getActivity(),
									getResources().getString(R.string.upload),
									getResources().getString(R.string.loading),
									true);

							userDao.upLoadPhoto(avatar_pic, getActivity(),
									dialog);
						} else {

							if (dialog != null)
								dialog.dismiss();

							Toast.makeText(getActivity(), "File is too large!",
									Toast.LENGTH_SHORT).show();
						}

					} catch (Exception e) {
						Log.e("FileSelectorTestActivity", "File select error",
								e);
					}
				}
			}
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onResume() {
		super.onResume();
		imageFetcher.setExitTasksEarly(false);
	}

	@Override
	public void onPause() {
		super.onPause();
		imageFetcher.setPauseWork(false);
		imageFetcher.setExitTasksEarly(true);
		imageFetcher.flushCache();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		imageFetcher.closeCache();
	}

	private void showChooser() {
		// Use the GET_CONTENT intent from the utility class
		Intent target = FileUtils.createGetContentIntent();
		// Create the chooser Intent
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));
		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			// The reason for the existence of aFileChooser
		}
	}

	private String getBitmap(String tag, Uri url) {
		File cacheDir;
		// if the device has an SD card
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			cacheDir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					".OCFL311");
		} else {
			// it does not have an SD card
			cacheDir = getActivity().getCacheDir();
		}
		if (!cacheDir.exists())
			cacheDir.mkdirs();

		File f = new File(cacheDir, tag);
		try {
			if (f.exists()) {
				f.delete();
				f.createNewFile();
			} else {
				f.createNewFile();
			}

		} catch (Exception e) {

		}
		try {
			InputStream is = null;
			if (url.toString().startsWith(
					"content://com.google.android.gallery3d")) {
				is = getActivity().getContentResolver().openInputStream(url);
			} else {
				is = new URL(url.toString()).openStream();
			}
			OutputStream os = new FileOutputStream(f);

			byte[] buffer = new byte[1024];
			int len;
			while ((len = is.read(buffer)) != -1) {
				os.write(buffer, 0, len);
			}

			os.close();
			return f.getAbsolutePath();
		} catch (Exception ex) {
			// something went wrong
			ex.printStackTrace();
			return null;
		}
	}

	private void init() {

		handler = new Handler();

		userDao = new UserDAO();

		my_avatar = (RecyclingImageView) getActivity().findViewById(
				R.id.my_avatar);

		my_avatar = (RecyclingImageView) getActivity().findViewById(
				R.id.my_avatar);
		my_first_name = (TextView) getActivity().findViewById(
				R.id.my_first_name);
		my_last_name = (TextView) getActivity().findViewById(R.id.my_last_name);
		my_email = (TextView) getActivity().findViewById(R.id.my_email);
		my_male = (RadioButton) getActivity().findViewById(R.id.my_male);
		my_female = (RadioButton) getActivity().findViewById(R.id.my_female);
		my_age_group = (Spinner) getActivity().findViewById(
				R.id.my_age_range_spinner);
		my_region = (Spinner) getActivity()
				.findViewById(R.id.my_region_spinner);

		update = (Button) getActivity().findViewById(R.id.my_update);

		facebookAge = (TextView)getActivity().findViewById(R.id.facebook_age);
		facebookRegion = (TextView)getActivity().findViewById(R.id.facebook_region);
		
		ImageCacheParams cacheParams = new ImageCacheParams(getActivity(),
				IMAGE_CACHE_DIR);

		imageFetcher = new ImageFetcher(getActivity(), mImageThumbSize);
		imageFetcher.setLoadingImage(R.drawable.user);
		imageFetcher.addImageCache(
				((FragmentActivity) getActivity()).getSupportFragmentManager(),
				cacheParams);
	}

	private void execute() {

		if (ContentManager.getInstance().isLogin()) {
			User user = ContentManager.getInstance().getCurrentUser();

			my_email.setText(user.getEmail());
			my_first_name.setText(user.getFirst_name());
			my_last_name.setText(user.getLast_name());
			imageFetcher.loadImage(user.getAvatar(), my_avatar);

			if (user.getUser_facebook_id() != null
					&& user.getUser_facebook_id() != "") {

				facebookAge.setVisibility(View.VISIBLE);
				facebookRegion.setVisibility(View.VISIBLE);
				
				my_region.setVisibility(View.GONE);
				my_age_group.setVisibility(View.GONE);
				
				facebookAge.setText(user.getAge());
				facebookRegion.setText(user.getRegion());
				
				my_male.setEnabled(false);
				my_female.setEnabled(false);
				
				
			} else {

				my_male.setEnabled(true);
				my_female.setEnabled(true);
				
				facebookAge.setVisibility(View.GONE);
				facebookRegion.setVisibility(View.GONE);
				
				my_region.setVisibility(View.VISIBLE);
				my_age_group.setVisibility(View.VISIBLE);
				
				for (int i = 0; i < my_region.getCount(); i++) {
					if (my_region.getItemAtPosition(i).toString()
							.equals(user.getRegion())) {
						my_region.setSelection(i);
						break;
					}
				}

				for (int i = 0; i < my_age_group.getCount(); i++) {
					if (my_age_group.getItemAtPosition(i).toString()
							.equals(user.getAge())) {
						my_age_group.setSelection(i);
						break;
					}
				}

				
			}
			
			if (user.getSex().equals("male") || user.getSex().equals("0")) {
				my_male.setChecked(true);
			} else {
				my_male.setChecked(false);
			}

		}

		update.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				User user = new User();

				user.setSex(my_male.isChecked() ? "male" : "female");
				user.setFirst_name(my_first_name.getText().toString().trim());
				user.setLast_name(my_last_name.getText().toString().trim());
				user.setAge(my_age_group.getSelectedItem().toString());
				user.setRegion(my_region.getSelectedItem().toString());

				dialog = ProgressDialog.show(getActivity(), getResources()
						.getString(R.string.update_info), getResources()
						.getString(R.string.loading), true);

				userDao.updateMySelf(user, handlerUpdateInfo, getActivity(),
						dialog);
			}
		});

		String avatar_str = ContentManager.getInstance().getCurrentUser()
				.getAvatar();

		imageFetcher.loadImage(avatar_str, my_avatar);

		my_avatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showChooser();
			}
		});
	}

	AsyncHttpResponseHandler handlerUpdateInfo = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Update Success");

			ContentManager.getInstance().getCurrentUser()
					.setSex(my_male.isChecked() ? "male" : "female");
			ContentManager.getInstance().getCurrentUser()
					.setFirst_name(my_first_name.getText().toString().trim());
			ContentManager.getInstance().getCurrentUser()
					.setLast_name(my_last_name.getText().toString().trim());
			ContentManager.getInstance().getCurrentUser()
					.setAge(my_age_group.getSelectedItem().toString());
			ContentManager.getInstance().getCurrentUser()
					.setRegion(my_region.getSelectedItem().toString());

			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}
	};

}
